package com.www.bigevent.controller;

import com.www.bigevent.pojo.Result;
import com.www.bigevent.pojo.User;
import com.www.bigevent.service.UserService;
import com.www.bigevent.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @PostMapping("/register")
    public Result register(String username,String password){
        //参数校验
        if(username!=null&&username.length()>=5&&username.length()<=16&&
           password!=null&&password.length()>=5&&password.length()<=16)
        {
            //查询用户
            User u=userService.findByusername(username);
            if (u==null){
                //没有占用
                //注册
                userService.register(username,password);
                return Result.success();
            }
            else{
                //占用
                return Result.error("用户名已存在");
            }
        }
        else{
            return Result.error("参数不合法");
        }
    }

    @PostMapping("/login")
    public Result<String> login(String username,String password){
            //根据用户名查询用户
            User loginuser=userService.findByusername(username);
            //判断用户是否存在
            if (loginuser==null){
                return Result.error("用户名错误");
            }
            //判断密码是否正确
            else if (password.equals(loginuser.getPassword())){
                //登录成功
                //生成Token
                Map<String,Object> claims=new HashMap<>();
                claims.put("id",loginuser.getId());
                claims.put("username",loginuser.getUsername());
                String token = JwtUtils.genToken(claims);
                return  Result.success(token);
            }
            return Result.error("密码错误");
    }
   @GetMapping("/userinfo")
    public Result<User> userinfo(@RequestHeader(name = "Authorization") String token) {
        //根据用户名查询用户
        //验证token
        Map<String, Object> map = JwtUtils.parseToken(token);
        String username = (String) map.get("username");

        User user = userService.findByusername(username);
        return Result.success(user);
    }

}
